package com.good.child.ui.activity.camera;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.good.child.MainActivity;
import com.good.child.R;
import com.good.child.bean.GenerateBean;
import com.good.child.iview.EmptyIView;
import com.good.child.pressent.EmptyPresenter;
import com.good.child.ui.activity.constants.Constants;
import com.good.child.ui.utils.AIHelpUtil;
import com.good.child.ui.utils.FileHelper;
import com.good.child.widgets.dialog.PreviewDialog;
import com.google.android.material.tabs.TabLayout;
import com.sjy.pickphotos.pickphotos.PhotoPicker;
import com.sjy.pickphotos.pickphotos.listeners.OnResultListener;
import com.yimidida.library.base.BaseActivity;
import com.yimidida.library.tool.TActivityUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shouheng.icamera.CameraView;
import me.shouheng.icamera.enums.CameraFace;
import me.shouheng.icamera.listener.CameraOpenListener;
import me.shouheng.icamera.listener.CameraPhotoListener;

/**
 * Create on: 2024/2/27
 * by Mr.Zhu
 * Description: TODO
 */
public class CameraActivity extends BaseActivity<EmptyIView, EmptyPresenter> {

    private final static String TAG = "CameraActivity";
    private static Context me;
    @BindView(R.id.cv)
    CameraView cameraView;
    @BindView(R.id.iv_switch)
    AppCompatImageView ivSwitch;
    //    @BindView(R.id.iv_shot)
//    AppCompatImageView ivShot;
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.tab_layout1)
    TabLayout tabLayout1;

    @BindView(R.id.tab_layout2)
    TabLayout tabLayout2;

//    @BindView(R.id.picker)
//    BitmapScrollPicker picker;

    private List<TabLayout.Tab> tabs = new ArrayList<>();

    private Map<String, String> aiMap = new HashMap<>();

    private String selectStyleCode = "", selectStyleName = "";
    private int picType = 0;
    private int picPostion = 0;

    //    FilterTexturePreview filterTexturePreview;
    @Override
    protected EmptyPresenter initPresenter() {
        return new EmptyPresenter(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        ButterKnife.bind(this);
        me = this;
        initView();
    }

    @Override
    protected void initView() {
        setStatusBar(false, false);
        setAndroidNativeLightStatusBar(this, true);
//        filterTexturePreview=new FilterTexturePreview((Context) this, (ViewGroup) rootView.getParent());
//        List<Bitmap> bitmaps = new ArrayList<>();
//        bitmaps.add(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_ai));
//        bitmaps.add(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_take));
//        bitmaps.add(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_mei));
//
//        picker.setData(bitmaps);
//        picker.setOnSelectedListener(new ScrollPickerView.OnSelectedListener() {
//            @Override
//            public void onSelected(ScrollPickerView scrollPickerView, int i) {
//                if (i == 0) {
//                    tabLayout1.setVisibility(View.VISIBLE);
//                    tabLayout2.setVisibility(View.INVISIBLE);
//                } else if (i == 1) {
//                    tabLayout1.setVisibility(View.INVISIBLE);
//                    tabLayout2.setVisibility(View.INVISIBLE);
//                } else if (i == 2) {
//                    tabLayout1.setVisibility(View.INVISIBLE);
//                    tabLayout2.setVisibility(View.VISIBLE);
//                }
//            }
//        });
//        picker.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                takePicture(picker.getSelectedPosition());
//            }
//        });
        setTitle("相机");
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.disney_3d_style, Constants.DISNEY_3D_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.real_mix_style, Constants.REAL_MIX_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.pastel_boys_style, Constants.PASTEL_BOYS_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.cartoon_style, Constants.CARTOON_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.makoto_style, Constants.MAKOTO_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.rev_animated_style, Constants.REV_ANIMATED_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.blueline_style, Constants.BLUELINE_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.water_ink_style, Constants.WATER_INK_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.water_paint_style, Constants.WATER_PAINT_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.comic_monet_style, Constants.COMIC_MONET_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.comic_marvel_style, Constants.COMIC_MARVEL_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.comic_future_style, Constants.COMIC_FUTURE_STYLE_NAME)));
        tabLayout1.addTab(tabLayout1.newTab().setCustomView(createCustomTabView(R.mipmap.exquisite_style, Constants.EXQUISITE_STYLE_NAME)));

        TabLayout.Tab tab14 = tabLayout2.newTab();
        TabLayout.Tab tab15 = tabLayout2.newTab();
        TabLayout.Tab tab16 = tabLayout2.newTab();
        TabLayout.Tab tab17 = tabLayout2.newTab();
        TabLayout.Tab tab18 = tabLayout2.newTab();
        TabLayout.Tab tab19 = tabLayout2.newTab();
        /*迪士尼3D风、写实风、天使风、动漫风、日漫风、公主风、梦幻风、水墨风、水彩风、莫奈花园、美式漫画、赛博机械/机甲风、韩漫*/
        aiMap.put(Constants.DISNEY_3D_STYLE_NAME, Constants.DISNEY_3D_STYLE_CODE);
        aiMap.put(Constants.REAL_MIX_STYLE_NAME, Constants.REAL_MIX_STYLE_CODE);
        aiMap.put(Constants.PASTEL_BOYS_STYLE_NAME, Constants.PASTEL_BOYS_STYLE_CODE);
        aiMap.put(Constants.CARTOON_STYLE_NAME, Constants.CARTOON_STYLE_CODE);
        aiMap.put(Constants.MAKOTO_STYLE_NAME, Constants.MAKOTO_STYLE_CODE);
        aiMap.put(Constants.REV_ANIMATED_STYLE_NAME, Constants.REV_ANIMATED_STYLE_CODE);
        aiMap.put(Constants.BLUELINE_STYLE_NAME, Constants.BLUELINE_STYLE_CODE);
        aiMap.put(Constants.WATER_INK_STYLE_NAME, Constants.WATER_INK_STYLE_CODE);
        aiMap.put(Constants.WATER_PAINT_STYLE_NAME, Constants.WATER_PAINT_STYLE_CODE);
        aiMap.put(Constants.COMIC_MONET_STYLE_NAME, Constants.COMIC_MONET_STYLE_CODE);
        aiMap.put(Constants.COMIC_MARVEL_STYLE_NAME, Constants.COMIC_MARVEL_STYLE_CODE);
        aiMap.put(Constants.COMIC_FUTURE_STYLE_NAME, Constants.COMIC_FUTURE_STYLE_CODE);
        aiMap.put(Constants.EXQUISITE_STYLE_NAME, Constants.EXQUISITE_STYLE_CODE);

        tab14.setText("复古");
        tab15.setText("现代");
        tab16.setText("自然");
        tab17.setText("艺术");
        tab18.setText("生活");
        tab19.setText("黑白");

        tab14.setIcon(R.mipmap.ic_mofa);
        tab15.setIcon(R.mipmap.ic_mofa);
        tab16.setIcon(R.mipmap.ic_mofa);
        tab17.setIcon(R.mipmap.ic_mofa);
        tab18.setIcon(R.mipmap.ic_mofa);
        tab19.setIcon(R.mipmap.ic_mofa);

        tabLayout2.addTab(tab14);
        tabLayout2.addTab(tab15);
        tabLayout2.addTab(tab16);
        tabLayout2.addTab(tab17);
        tabLayout2.addTab(tab18);
        tabLayout2.addTab(tab19);
        tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                tab.select();
                TextView textView = tab.getCustomView().findViewById(R.id.tabText);
                ToastUtils.showShort("选择了" + textView.getText());
                selectStyleName = textView.getText().toString();
                selectStyleCode = aiMap.get(selectStyleName);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        tabLayout2.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                ToastUtils.showShort("选择了" + tab.getText());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        tabLayout1.setVisibility(View.VISIBLE);
        tabLayout2.setVisibility(View.INVISIBLE);
        selectStyleName = Constants.DISNEY_3D_STYLE_NAME;
        selectStyleCode = aiMap.get(selectStyleName);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cameraView != null) {
            cameraView.releaseCamera();
            cameraView = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!cameraView.isCameraOpened()) {
            cameraView.openCamera(new CameraOpenListener() {
                @Override
                public void onCameraOpened(int i) {
                    Log.d(TAG, "onCameraOpened: " + i);
                }

                @Override
                public void onCameraOpenError(@NonNull Throwable throwable) {
                    Log.d(TAG, "onCameraOpenError: " + throwable);
                }
            });
        }
    }


    @OnClick({R.id.iv_switch, R.id.iv_close, R.id.tv_star, R.id.tv_mouse, R.id.tv_photo, R.id.iv_take})
    public void onClickView(View view) {
        switch (view.getId()) {
            case R.id.iv_switch:
                if (cameraView.getCameraFace() == CameraFace.FACE_FRONT) {
                    cameraView.switchCamera(CameraFace.FACE_REAR);
                } else {
                    cameraView.switchCamera(CameraFace.FACE_FRONT);
                }
                break;
            case R.id.iv_close:
                finish();
                break;
            case R.id.tv_star:
                tabLayout1.setVisibility(View.VISIBLE);
                tabLayout1.selectTab(tabLayout1.getTabAt(0));
                tabLayout2.setVisibility(View.INVISIBLE);
                picType = 0;
                break;
            case R.id.tv_mouse:
                tabLayout1.setVisibility(View.INVISIBLE);
                tabLayout2.setVisibility(View.VISIBLE);
                tabLayout2.selectTab(tabLayout1.getTabAt(0));
                picType = 1;
                break;
            case R.id.tv_photo:
                pickImage();
                break;
            case R.id.iv_take:
                takePicture();
                break;
        }
    }

    private void pickImage() {
        PhotoPicker.Album(this).setMultiChooseSize(1).setIsCompress(true)//是否压缩
                .setIsCrop(false)//是否裁切
                .setOnResultListener(new OnResultListener() {
                    @Override
                    public void onSucess(ArrayList<String> imagePathList) {
                        if (imagePathList.size() >= 1) {
                            requestImage(new File(imagePathList.get(0)));
                        } else {
                            ToastUtils.showShort("选择异常");
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                }).start();
    }

    private void takePicture() {
        File fileToSave = FileHelper.getSavedFile("jpg");
        cameraView.takePicture(fileToSave, new CameraPhotoListener() {
            @Override
            public void onPictureTaken(@NonNull byte[] bytes, @NonNull File file) {
                requestImage(file);
//                showLoading("照片生成中，请等待", result -> {
//                    int rotateDegree = ImageUtils.getRotateDegree(file.getAbsolutePath());
//                    Bitmap bitmap = ImageUtils.rotate(ImageUtils.getBitmap(file), rotateDegree, 0f, 0f);
//                    if (bitmap == null) {
//                        ToastUtils.showShort("图像生成失败");
//                        return;
//                    }
//                    if (selectedPosition == 0) {//AI特效
//
//                    } else if (selectedPosition == 1) {
//
//                    } else if (selectedPosition == 2) {
//
//                    }
//                    ivImg.setImageBitmap(bitmap);
//                    clPic.setVisibility(View.VISIBLE);
//
//
//                });
//                FileHelper.saveImageToGallery(me, fileToSave, fileToSave.getName());
//                Log.d(TAG, "Path: " + file.getPath());
//                Log.d(TAG, "AbsolutePath: " + file.getAbsolutePath());
//                ToastUtils.showShort("Saved to " + file.getAbsolutePath());
            }

            @Override
            public void onCaptureFailed(@NonNull Throwable throwable) {
                ToastUtils.showShort("onCaptureFailed : ");

            }
        });
    }

    private void requestImage(File file) {
        showLoading("照片生成中，请等待");
        try {
            AIHelpUtil.getInstance().requestAICamera(selectStyleCode, file, new AIHelpUtil.Text2TextCallBack() {
                @Override
                public void onDataBack(GenerateBean generateBean) {
                    if (generateBean == null) {
                        return;
                    }
//                clPic.setVisibility(View.VISIBLE);
                    runOnUiThread(() -> {
                        hideLoading();
                        PreviewDialog.showDialog(getSupportFragmentManager(), generateBean.getFileUrl(), true);
                    });

                }
            });
        } catch (Exception e) {
            LogUtils.eTag("requestImage", e);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_HOME) {
            TActivityUtils.jumpToActivity(getBaseContext(), MainActivity.class);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private View createCustomTabView(int icon, String text) {
        View view = getLayoutInflater().inflate(R.layout.tab_layout, null);
        view.setLayoutParams(new ViewGroup.LayoutParams(
                TabLayout.LayoutParams.MATCH_PARENT, TabLayout.LayoutParams.MATCH_PARENT));
        ImageView tabIcon = view.findViewById(R.id.tabIcon);
        TextView tabText = view.findViewById(R.id.tabText);
        tabIcon.setImageResource(icon);
        tabText.setText(text);
        return view;
    }
}
